//
//  PPFoundViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/27/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPFoundViewController.h"
#import "PPFoundSearchViewController.h"
#import "PPTimelinePictureViewController.h"
#import "PPWebViewViewController.h"
#import "PPMessageTimelineViewController.h"
#import "PPTimelineDetailViewController.h"
#import "PPFoundTimelineViewController.h"

#import "PPFoundTableViewCell.h"

#import "PPAlbumObject.h"

#import "ZYBannerView.h"

#import "PPUnreadMessageManager.h"

static const NSInteger kCount = 30;
@interface PPFoundViewController () <UITextFieldDelegate, PPFoundTableViewCellDelegate, ZYBannerViewDataSource, ZYBannerViewDelegate>
@property (readwrite, nonatomic, strong) NSArray *banners;
@property (nonatomic, strong) NSNumber *next;
@property (nonatomic, assign) NSInteger page;
@end

@implementation PPFoundViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _page = 1;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.tableView registerNib:[UINib nibWithNibName:@"PPFoundTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];

    UITextField *searchField = [[UITextField alloc] init];
    searchField.font = [UIFont systemFontOfSize:14];
    searchField.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
    searchField.frame = CGRectMake(0, 0, 275, 25);
    searchField.layer.cornerRadius = 5;
    searchField.layer.masksToBounds = YES;
    searchField.backgroundColor = [UIColor colorWithRGBHex:0xffffff alpha:0.1];
    searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0x999999]}];
    searchField.delegate = self;
    searchField.enablesReturnKeyAutomatically = YES;

    UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-search"]];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [iconView sizeToFit];
    iconView.width += 20;
    searchField.leftView = iconView;
    searchField.leftViewMode = UITextFieldViewModeAlways;

    self.navigationItem.titleView = searchField;

    [self fetchBannerData];

    [self updateNavigationBar];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveUnreadMessageSummaryDidChangeNotification) name:PPUnreadMessageSummaryDidChangeNotification object:nil];
}

- (void)didReceiveUnreadMessageSummaryDidChangeNotification {
    [self updateNavigationBar];
}

- (void)updateNavigationBar {
    PPUnreadMessageSummaryObject *summary = [[PPUnreadMessageManager sharedInstance] summaryForType:PPUnreadMessageSummaryTypeFound];

    UIImage *icon = [UIImage imageNamed:@"but-message"];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [button setImage:icon forState:UIControlStateNormal];
    [button sizeToFit];
    button.imageView.layer.cornerRadius = button.imageView.width/2;
    button.imageView.layer.masksToBounds = YES;

    if(summary != nil && summary.count.integerValue > 0) {
        if ([summary.iconURLString length]) {
            [button sd_setImageWithURL:[NSURL URLWithString:summary.iconURLString] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRetryFailed];
        } else {
            [button setImage:[UIImage imageNamed:@"system_message_icon_small"] forState:UIControlStateNormal];
        }

    }

    UIBarButtonItem *moreItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    UIBarButtonItem *negItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negItem.width = -10;

    self.navigationItem.rightBarButtonItems = @[negItem, moreItem];

    __weak typeof(self)weakSelf = self;
    [button setActionBlock:^(UIControl *control) {
        [MobClick event:@"118"];
        [weakSelf moreItemDidPressed:moreItem];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)fetchBannerData {
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchPublicBannerWithCallback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveBannerResult:data error:error];
    }];
}

- (void)didReceiveBannerResult:(NSDictionary *)result error:(NSError *)error {
    NSArray *banners = [result validArray];

    if(error != nil || banners.count == 0) {
        self.tableView.tableHeaderView = nil;
    } else {
        _banners = banners;

        ZYBannerView *bannerView = [[ZYBannerView alloc] init];
        bannerView.dataSource = self;
        bannerView.delegate = self;
        bannerView.shouldLoop = YES;
        bannerView.autoScroll = YES;
        bannerView.scrollInterval = 2;
        bannerView.frame = CGRectMake(0, 0, self.tableView.width, self.tableView.width/2);
        self.tableView.tableHeaderView = bannerView;
    }

    [self.tableView reloadData];
}

- (void)moreItemDidPressed:(UIBarButtonItem *)item {
    PPMessageTimelineViewController *messageViewConroller = [[PPMessageTimelineViewController alloc] init];
    messageViewConroller.summaryType = PPUnreadMessageSummaryTypeFound;
    [self.navigationController pushViewController:messageViewConroller animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier:@"cell" cacheByIndexPath:indexPath configuration:^(id cell) {

    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.items.count == 0) {
        return 0;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ceil(self.items.count/3.0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(tableView.tableHeaderView != nil) {
        return 46;
    } else {
        return CGFLOAT_MIN;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] init];
    header.frame = CGRectMake(0, 0, tableView.width, 46);
    header.backgroundColor = [UIColor clearColor];
    header.clipsToBounds = YES;

    UILabel *label = [[UILabel alloc] init];
    label.text = @"热门图册";
    label.textColor = [UIColor colorWithRGBHex:0x323232];
    label.font = [UIFont systemFontOfSize:16];
    [label sizeToFit];
    label.left = 14;
    label.centerY = header.height/2;
    [header addSubview:label];

    return header;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    PPAlbumObject *leftAlbum = [self.items safeObjectAtIndex:(indexPath.row*3)];

    PPAlbumObject *middleAlbum = [self.items safeObjectAtIndex:(indexPath.row*3 + 1)];

    PPAlbumObject *rightAlbum = [self.items safeObjectAtIndex:(indexPath.row*3 + 2)];

    ((PPFoundTableViewCell *)cell).leftAlbum = leftAlbum;
    ((PPFoundTableViewCell *)cell).middleAlbum = middleAlbum;
    ((PPFoundTableViewCell *)cell).rightAlbum = rightAlbum;
    ((PPFoundTableViewCell *)cell).delegate = self;

    return cell;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [MobClick event:@"114"];
    PPFoundSearchViewController *searchViewController = [[UIStoryboard storyboardWithName:@"Found" bundle:nil] instantiateViewControllerWithIdentifier:@"PPFoundSearchViewController"];
    [self.navigationController pushViewController:searchViewController animated:NO];

    return NO;
}

- (void)showsEmptyIfNeeded {
    UIView *footerView = [self.scrollWrapper valueForKey:@"footerView"];
    UIActivityIndicatorView *activityView = [self valueForKey:@"loadMoreIndicatorView"];

    UILabel *label = objc_getAssociatedObject(footerView, "emptyLabel");

    if(_next.integerValue != -1) {
        activityView.hidden = NO;
        label.hidden = YES;
    } else {
        activityView.hidden = YES;

        if(label == nil) {
            label = [[UILabel alloc] init];
            label.font = [UIFont systemFontOfSize:14];
            label.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
            label.text = @"已显示全部";
            [label sizeToFit];
            [footerView addSubview:label];

            objc_setAssociatedObject(footerView, "emptyLabel", label, OBJC_ASSOCIATION_RETAIN);
        }

        label.centerX = footerView.width/2;
        label.top = 30;
        label.hidden = NO;
    }
}

#pragma mark - Timeline

- (void)fetchNewItems {
    [super fetchNewItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchDiscoverWithPage:@(1) limit:@(kCount) callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [MobClick event:@"120"];
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchDiscoverWithPage:@(_page + 1) limit:@(kCount) callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveMoreResult:data ? : error];
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    _page = 1;
    NSArray *items = [super didReceiveNewResult:result];

//    if([_next integerValue] != -1) {
//        self.scrollWrapper.enableLoadMore = YES;
//    } else {
//        self.scrollWrapper.enableLoadMore = NO;
//    }

    [self showsEmptyIfNeeded];

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    _page ++;
    NSArray *items = [super didReceiveMoreResult:result];


//    if([_next integerValue] != -1) {
//        self.scrollWrapper.enableLoadMore = YES;
//    } else {
//        self.scrollWrapper.enableLoadMore = NO;
//    }

    [self showsEmptyIfNeeded];

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];

    for(NSDictionary *parameters in [result validArrayForKey:@"albums"]) {
        PPAlbumObject *album = [PPAlbumObject albumForParameters:parameters];
        [items addObject:album];
    }

    return items;
}

#pragma mark - PPFoundTableViewCellDelegate

- (void)foundCell:(PPFoundTableViewCell *)foundCell didSelectAlbum:(PPAlbumObject *)album {
    [MobClick event:@"119"];
    PPFoundTimelineViewController *timelineViewController = [[PPFoundTimelineViewController alloc] init];
    timelineViewController.albums = self.items;
    timelineViewController.index = [self.items indexOfObject:album];
    timelineViewController.next = _next;
    timelineViewController.page = _page;
    [self.navigationController pushViewController:timelineViewController animated:YES];
}

#pragma mark - ZYBannerViewDataSource

- (NSInteger)numberOfItemsInBanner:(ZYBannerView *)banner {
    return _banners.count;
}

- (UIView *)banner:(ZYBannerView *)banner viewForItemAtIndex:(NSInteger)index {
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;

    NSDictionary *item = [_banners safeObjectAtIndex:index];

    NSString *url = [item validStringForKey:@"imgUrl"];

    [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageRetryFailed];

    return imageView;
}

#pragma mark - ZYBannerViewDelegate

- (void)banner:(ZYBannerView *)banner didSelectItemAtIndex:(NSInteger)index {
    NSDictionary *item = [_banners safeObjectAtIndex:index];

    NSString *url = [item validStringForKey:@"linkUrl"];

    PPWebViewViewController *webViewController = [[PPWebViewViewController alloc] init];
    webViewController.url = url;
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        DGAlignmentButton *button = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
        button.style = DGAlignmentButtonStyleImageTop;
        button.spacing = 10;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
        [button setImage:[UIImage imageNamed:@"logo-gred"] forState:UIControlStateNormal];
        [button setTitle:@"暂无内容" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        [button sizeToFit];

        return button;
    }
}

- (UIEdgeInsets)preferredScrollInsets {
    return UIEdgeInsetsMake(64 - 1, 0, 0, 0);
}

- (BOOL)scrollViewWrapperShouldTriggerLoadMore:(DGScrollViewWrapper *)scrollViewWrapper {
    if(_next.integerValue != -1) {
        return YES;
    }
    return NO;
}

@end
